package org.nimi317.web_gis.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import org.nimi317.web_gis.form.post.LoginPost;
import org.nimi317.web_gis.form.post.RegisterPost;
import org.nimi317.web_gis.entity.R;
import org.nimi317.web_gis.entity.User;
import org.nimi317.web_gis.service.IEmailService;
import org.nimi317.web_gis.service.IUserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author thunderobot
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    private final IEmailService emailService;

    private final IUserService userService;

    public LoginController(IEmailService emailService, IUserService userService) {
        this.emailService = emailService;
        this.userService = userService;
    }

    @PostMapping("login")
    public R<?> login(@RequestBody @Validated LoginPost loginPost) {
        String email = loginPost.getEmail();
        emailService.checkLoginCaptcha(email, loginPost.getCode());
        emailService.removeLoginCaptcha(email);
        User user = userService.getByEmail(email);
        StpUtil.login(user.getId());
        SaTokenInfo info = StpUtil.getTokenInfo();
        user.setToken(info);
        return R.ok(user);
    }

    @GetMapping("logout")
    @SaCheckLogin
    public R<?> logout() {
        StpUtil.logout();
        return R.ok();
    }

    @GetMapping("login/{email}")
    public R<?> sendCaptcha(@PathVariable String email) {
        emailService.sendLoginCaptcha(email);
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody @Validated RegisterPost registerPost) {
        String email = registerPost.getEmail();
        emailService.checkRegisterCaptcha(email, registerPost.getCode());
        emailService.removeRegisterCaptcha(email);
        User user = userService.createByEmail(email, registerPost.getUserName());
        StpUtil.login(user.getId());
        SaTokenInfo tokenValue = StpUtil.getTokenInfo();
        user.setToken(tokenValue);
        return R.ok(user);
    }

    @GetMapping("register/{email}")
    public R<?> sendRegisterCaptcha(@PathVariable String email) {
        emailService.sendRegisterCaptcha(email);
        return R.ok();
    }
}
